<!--
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-05-17 19:37:02
 * @LastEditTime : 2020-01-14 13:53:11
 * @LastEditors  : Please set LastEditors
 -->
<template>
  <search-table
	    ref="searchTable"
		  :columns="tbTitle" 
      :data="tbData"
      :total="pageCount"
      :page.sync="connfigerCurrentPage"
      :size.sync="configerItemPage"
      @change-size="switchConfigerItemPage"
      @change-page="switchineConfigerCurrentPage"
      :showPage="false"
	>
  <template name="search">
      <Button
        type="primary"
        @click="
          addConfigureBt = true;
          addConfigureBtTitle = '创建配置';
          cancelsmtConfigureInfo('formValidate');
        "
      >
        <Icon type="md-add" />
        创建配置
      </Button>
      <Input
        suffix="ios-search"
        placeholder="请输入名称"
        clearable
        style="width: auto"
        v-model="btnNameValue"
        @on-change="
          connfigerCurrentPage = 1;
          getQgaExecuteCmdInfoList();
        "
      />
      <Select filterable
        v-model="configerSystypeOfReach"
        filterable
        style="width:180px;"
        clearable
        transfer 
        placeholder="请选择系统"
        @on-change="
          connfigerCurrentPage = 1;
          getQgaExecuteCmdInfoList();
        "
      >
        <Option value="linux">Linux</Option>
        <Option value="windows">Windows</Option>
      </Select>
      <DatePicker
        type="daterange"
        split-panels
        placeholder="请选择日期"
        style="width: 200px"
        :editable="false"
        v-model="configerDateSelected"
        @on-change="dateSelected"
        :options="options3"
      ></DatePicker>
      <!-- <Button type="primary"  @click="getQgaExecuteCmdInfoList">搜索</Button> -->
      <Checkbox v-model="createType" label="inside" v-show="isShowInputs == 1"
        >展示“一键导入配置”的配置</Checkbox
      >
      <!-- <Page
        :total="pageCount"
        show-total
        style="float:right;"
        show-sizer
        :current="connfigerCurrentPage"
        :page-size="configerItemPage"
        @on-change="switchineConfigerCurrentPage"
        @on-page-size-change="switchConfigerItemPage"
      /> -->
  </template>
  <Modal
      v-model="addConfigureBt"
      :title="addConfigureBtTitle"
      :loading="loading"
      :mask-closable="false"
      @on-ok="submitConfigureInfo('formValidate')"
      @on-cancel="cancelsmtConfigureInfo('formValidate')"
    >
      <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="95">
        <FormItem label="名称" prop="name">
          <Input v-model="formValidate.name" placeholder="请输入名称" :maxlength="64"></Input>
        </FormItem>
        <FormItem label="操作系统" prop="osType">
          <RadioGroup v-model="formValidate.osType">
            <Radio label="Windows">Windows</Radio>
            <Radio label="Linux">Linux</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="指令" prop="cmd">
          <Input v-model="formValidate.cmd" placeholder="请输入配置指令"></Input>
        </FormItem>
        <FormItem label="可见范围" prop="visibility">
          <RadioGroup v-model="formValidate.visibility">
            <!-- <Radio label="public" >系统</Radio> -->
            <Radio label="share">单位</Radio>
            <Radio label="private">个人</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="描述" prop="description">
          <Input
            v-model="formValidate.description"
            type="textarea"
            :rows="2"
            :maxlength="200"
          ></Input>
        </FormItem>
        <Collapse v-model="panelValue" simple accordion>
          <Panel name="1">
            高级扩展
            <p slot="content">
              <FormItem
                v-for="(item, index) in formValidate.items"
                v-if="item.status"
                :key="index"
                :label="'参数 ' + parseInt(index + 1)"
                :prop="'items.' + index + '.value'"
              >
                <Row>
                  <Col span="11">
                    <Input type="text" v-model="item.value" placeholder="输入指令参数"></Input>
                  </Col>
                  <Col span="12" offset="1">
                    <Button @click="handleAdd(index)" type="dashed" icon="md-add">Add</Button>
                    <Button @click="handleRemove(index)" type="dashed" icon="md-remove"
                      >Delete</Button
                    >
                  </Col>
                </Row>
              </FormItem>
              <FormItem>
                <Row>
                  <Col span="12">
                    <Button
                      type="dashed"
                      long
                      @click="handleAdd(formValidate.items.length - 1)"
                      icon="md-add"
                      >添加指令参数</Button
                    >
                  </Col>
                </Row>
              </FormItem>
            </p>
          </Panel>
        </Collapse>
      </Form>
    </Modal>

    <Modal v-model="delConfigureMd" title="删除配置" @on-ok="ok4delConfigureMd">
      <div style="text-align:center;font-size:15px;">
        确认要删除配置：" <strong>{{ this.currConfigureName }}</strong> " 吗？
      </div>
    </Modal>
    <Modal v-model="detailConfigureMd" title="配置详情">
      <Table stripe :columns="detailTbTitle" :data="detailTbData" :show-header="false"></Table>
    </Modal>
</search-table>
</template>
<script>
const validateNameCNLU = (rule, value, callback) => {
  var myReg = /[~!！@#$%^&*()/\|,<>?"'“‘();:+=\[\]{}]/;
  value = value.replace(/\s*/g, '');
  if (!value) {
    callback('请填写名称');
  } else {
    if (myReg.test(value)) {
      callback('名称不能包含特殊字符');
    } else {
      callback();
    }
  }
};
import axios from '@/libs/axios1';
// import TableTooltip from '@/components/common/tableTooltip.vue';
export default {
  name: 'qgaexecute',
  // components: { TableTooltip },
  data() {
    return {
      options3: {
        disabledDate(date) {
          return date && date.valueOf() > Date.now();
        }
      },
      configerItemPage: 10,
      connfigerCurrentPage: 1,
      configerSystypeOfReach: '',
      configerStartTime: '',
      configerEndTime: '',
      configerDateSelected: '',
      timeInterval: 0,
      tableHeight: '',
      btnNameValue: '',
      tbTitle: [
        {
          title: '名称',
          key: 'name',
          align: 'center',
          minWidth:100,
          tooltip: true
        },
        { title: '操作系统', key: 'osType', align: 'center', minWidth:100, tooltip: true },
        {
          title: '指令',
          key: 'cmd',
          align: 'center',
          minWidth:100,
          filter:(cmd,data) => data.data.cmd
        },
        {
          title: '参数',
          key: 'arg',
          align: 'center',
          minWidth:100,
          filter:(arg,data) => data.data.arg
        },
        {
          title: '可见范围',
          key: '',
          align: 'center',
          minWidth:100,
          render: (h, params) => {
            let visibilityValue = null;
            if (params.row.visibility == 'public') {
              visibilityValue = '系统';
            } else if (params.row.visibility == 'share') {
              visibilityValue = '单位';
            } else if (params.row.visibility == 'private') {
              visibilityValue = '个人';
            } else {
              visibilityValue = '--';
            }
            return h('div', {}, visibilityValue);
          }
        },
        {
          title: '创建时间',
          key: 'createTime',
          align: 'center',
          minWidth:140,
          tooltip: true
        },
        {
          title: '创建者',
          key: 'creatorName',
          align: 'center',
          minWidth:100,
          tooltip: true
          // render:(h,params)=>{
          //     return h('div',{}, params.row.creatorName)
          // if(params.index==0){
          //     return h('div',{}, '贾海林');
          // }else{
          //     return h('div',{}, params.row.creatorName)
          // }
          // }
        },
        {
          title: '配置描述',
          key: 'description',
          align: 'center',
          minWidth:100,
          tooltip:true
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          width: 200,
          opList:[
            {
              txt:"修改",
              fun:this.modifyInfo
            },
            {
              txt:"删除",
              type:'delete',
              tooltip:true,
              title: '您确定要删除此配置吗？',
              fun:this.removeInfo
            }
          ]
        }
      ],
      formValidate: {
        name: '',
        osType: 'Windows',
        cmd: '',
        items: [
          {
            value: '',
            index: 1,
            status: 1
          }
        ],
        description: '',
        visibility: 'share'
      },
      ruleValidate: {
        name: [
          { required: true, message: '请填写名称！', trigger: 'blur', validator: validateNameCNLU }
        ],
        osType: [{ required: true, message: '请选择操作系统类型！', trigger: 'change' }],
        cmd: [{ required: true, message: '请填写配置指令！', trigger: 'blur' }]
      },
      tbData: [],
      detailTbData: [],
      loading: true,
      addConfigureBt: false,
      addConfigureBtTitle: '创建配置',
      currPage: 1,
      pageCount: 0,
      detailConfigureMd: false,
      detailTbTitle: [
        {
          title: '属性',
          key: 'attr'
        },
        {
          title: '值',
          key: 'value'
        }
      ],
      configureDetailInfo: {},
      delConfigureMd: false,
      currConfigureId: '',
      currConfigureName: '',
      panelValue: '1',
      index: 1,
      isShowInputs: 0,
      createType: ''
    };
  },
  props: ['refreshTaskList'],
  created: function() {
    // this.tableHeight = $(window).height() - 115 ;
    // this.getQgaExecuteCmdInfoList();
  },
  mounted() {
    this.isShowImportImport();
  },
  methods: {
    isShowImportImport() {
      let _this = this;
      axios({
        url: '/dictionaries/sysConf/getInfoByName?name=isShowInput',
        method: 'GET'
      })
        .then((response) => {
          if (response.code == 1) {
            _this.isShowInputs = response.attribute.data.defaultValue || 0;
          }
        })
        .catch(() => {});
    },
    dateSelected(value) {
      console.log(value);
      if (value[0]) {
        this.configerStartTime = String(value[0]) + ' 00:00:00';
        this.configerEndTime = String(value[1]) + ' 23:59:59';
      } else {
        this.configerStartTime = '';
        this.configerEndTime = '';
      }
      this.connfigerCurrentPage = 1;
      this.getQgaExecuteCmdInfoList();
    },
    change: function(page) {
      this.currPage = page;
      this.getQgaExecuteCmdInfoList();
    },
    getQgaExecuteCmdInfoList() {
      let _this = this;
      let data = {
        page: _this.connfigerCurrentPage,
        size: _this.configerItemPage,
        operation: 'qga_execute_cmd',
        name: _this.btnNameValue,
        osType: _this.configerSystypeOfReach,
        startTime: String(_this.configerStartTime),
        endTime: String(_this.configerEndTime)
      };
      if (this.createType) {
        data['createType'] = 'inside';
      }
      axios({
        url: '/tasktemplate/item',
        method: 'get',
        params: data
      }).then(function(response) {
        if (response.code != '1') {
          _this.$Message.info(response.message);
          _this.tbData = [];
        } else {
          _this.tbData = response.data.list.map(function(item) {
            return {
              id: item.id,
              name: item.name,
              osType: item.data.osType,
              description: item.description,
              data: item.data,
              visibility: item.visibility,
              createTime: item.createTime,
              creatorName: item.creatorName
            };
          });
          _this.pageCount = response.data.count;
        }
      });
    },
    getConfigureInfo(params) {
      let _this = this;
      _this.detailConfigureMd = true;
      _this.currConfigureId = params.row.id;
      axios({
        url: '/tasktemplate/item/' + _this.currConfigureId,
        method: 'get'
      }).then(function(response) {
        if (response.code != '1') {
          _this.$Message.info(response.message);
        } else {
          _this.configureDetailInfo = response.data;
          _this.detailTbData = [
            { attr: '名称', value: _this.configureDetailInfo.name },
            { attr: '配置描述', value: _this.configureDetailInfo.description },
            { attr: '操作系统', value: _this.configureDetailInfo.data.osType },
            { attr: '指令', value: _this.configureDetailInfo.data.cmd },
            { attr: '指令参数', value: _this.configureDetailInfo.data.arg },
            { attr: '可见范围', value: _this.configureDetailInfo.visibility },
            { attr: '创建时间', value: _this.configureDetailInfo.createTime },
            { attr: '创建者', value: _this.configureDetailInfo.creatorName },
            { attr: '修改时间', value: _this.configureDetailInfo.lastModifyTime },
            { attr: '修改者', value: _this.configureDetailInfo.modifior }
          ];
        }
      });
    },
    submitConfigureInfo(name) {
      let _this = this;
      this.$refs[name].validate((valid) => {
        if (valid) {
          _this.formValidate.arg = [];
          let data = _this.formValidate;
          data.name = data.name.replace(/\s*/g, '');
          _this.formValidate.items.forEach((item, i) => {
            if (item.status == 1 && item.value && item.value.trim() != '') {
              data.arg.push(item.value);
            }
          });
          if (_this.addConfigureBtTitle == '创建配置') {
            axios({
              url: '/tasktemplate/item/add/qga_execute_cmd',
              method: 'post',
              data: data
            }).then(function(response) {
              if (response.code != '1') {
                _this.$Message.error(response.message);
                _this.loading = false;
                _this.$nextTick(() => {
                  _this.loading = true;
                });
              } else {
                _this.$Message.success('创建配置完成!');
                _this.loading = false;
                _this.$nextTick(() => {
                  _this.loading = true;
                });
                _this.connfigerCurrentPage = 1;
                _this.configerItemPage = 10;
                _this.btnNameValue = '';
                _this.configerSystypeOfReach = '';
                _this.configerDateSelected = '';
                _this.configerStartTime = '';
                _this.configerEndTime = '';
                _this.createType = false;
                _this.getQgaExecuteCmdInfoList();
                _this.addConfigureBt = false;
                _this.cancelsmtConfigureInfo('formValidate');
              }
            });
          } else {
            //修改配置
            axios({
              url: '/tasktemplate/item/update/qga_execute_cmd/' + _this.currConfigureId,
              method: 'put',
              data: data
            }).then(function(response) {
              if (response.code != '1') {
                _this.$Message.error(response.message);
                _this.loading = false;
                _this.$nextTick(() => {
                  _this.loading = true;
                });
              } else {
                _this.$Message.success('修改配置完成!');
                _this.loading = false;
                _this.$nextTick(() => {
                  _this.loading = true;
                });
                _this.getQgaExecuteCmdInfoList();
                _this.addConfigureBt = false;
                _this.cancelsmtConfigureInfo('formValidate');
              }
            });
          }
        } else {
          _this.loading = false;
          _this.$nextTick(() => {
            _this.loading = true;
          });
          _this.$Message.info('请检查内容是否填写完整！');
        }
      });
    },
    cancelsmtConfigureInfo(name) {
      this.$refs[name].resetFields();
      this.formValidate = {
        name: '',
        osType: 'Windows',
        cmd: '',
        items: [
          {
            value: '',
            index: 1,
            status: 1
          }
        ],
        description: '',
        visibility: 'share'
      };
      this.index = 1;
    },
    modifyInfo(params) {
      let _this = this;
      _this.currConfigureId = params.id;
      axios({
        url: '/tasktemplate/item/' + _this.currConfigureId,
        method: 'get'
      }).then(function(response) {
        if (response.code != '1') {
          _this.$Message.error(response.message);
        } else {
          let argsTemp = [];
          let indexTemp = 0;
          response.data.data.arg.forEach((item, i) => {
            indexTemp = indexTemp + 1;
            let data = {
              value: item,
              index: indexTemp,
              status: 1
            };
            argsTemp.push(data);
          });
          _this.index = indexTemp;
          _this.formValidate = {
            name: response.data.name,
            osType: response.data.data.osType,
            cmd: response.data.data.cmd,
            items: argsTemp,
            description: response.data.description,
            visibility: response.data.visibility
          };
          _this.addConfigureBtTitle = '修改配置';
          _this.addConfigureBt = true;
        }
      });
    },
    removeInfo(params) {
      this.currConfigureId = params.id;
      this.ok4delConfigureMd();
    },
    ok4delConfigureMd() {
      let _this = this;
      axios({
        url: '/tasktemplate/item/' + _this.currConfigureId,
        method: 'delete'
      }).then(function(response) {
        if (response.code != '1') {
          _this.$Message.error(response.message);
        } else {
          _this.connfigerCurrentPage =
            _this.tbData.length == 1 && _this.connfigerCurrentPage > 1
              ? _this.connfigerCurrentPage - 1
              : _this.connfigerCurrentPage;
          _this.$Message.success('删除配置完成！');
          _this.getQgaExecuteCmdInfoList();
        }
      });
      _this.delConfigureMd = false;
    },
    handleAdd(index) {
      this.index++;
      this.formValidate.items.splice(index + 1, 0, {
        value: '',
        index: this.index,
        status: 1
      });
      // this.formValidate.items.push({
      //     value: '',
      //     index: this.index,
      //     status: 1
      // });
    },
    handleRemove(index) {
      this.formValidate.items.splice(index, 1);
      // this.formValidate.items[index].status = 0;
    },
    switchineConfigerCurrentPage(numberPage) {
      this.connfigerCurrentPage = numberPage;
      this.getQgaExecuteCmdInfoList();
    },
    switchConfigerItemPage(numberSize) {
      this.configerItemPage = numberSize;
      this.getQgaExecuteCmdInfoList();
    }
  },
  watch: {
    createType(val, oldVal) {
      //普通的watch监听
      console.log('createType: ' + val, oldVal);
      this.getQgaExecuteCmdInfoList();
    }
  }
};
</script>
